package com.lkx.controller;

import com.lkx.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName: com.lkx.controller.CommonController
 * @author: likaixin
 * @create: 2022年11月23日 9:49
 * @desc: 处理文件上传与下载的controller
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(@RequestPart("file") MultipartFile file) {
        log.info(file.toString());
        String filename = file.getOriginalFilename();
        File basePath = new File(this.basePath);
        if (!basePath.exists()) {
            //目录不存在，需要创建
            basePath.mkdirs();
        }
        try {
            UUID uuid = UUID.randomUUID();
            file.transferTo(new File(this.basePath + File.separator +  uuid+ filename.substring(filename.lastIndexOf("."))));
             filename=uuid.toString()+filename.substring(filename.lastIndexOf("."));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        response.setContentType("image/jpeg");

        try (    //输入流，通过输入流读取文件内容
                 FileInputStream fileInputStream = new FileInputStream(new File(basePath +File.separator+ name));
                 //输出流，通过输出流将文件写回浏览器，在浏览器展示图片了
                 ServletOutputStream outputStream = response.getOutputStream()) {
            byte[] bs = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(bs)) != -1) {
                outputStream.write(bs, 0, len);
                outputStream.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
